import axios from 'axios';
import { getToken } from '@/utils/auth';
import { ElMessage } from "element-plus"
import { Base64 } from 'js-base64';
import { validateJSON } from '@/utils/validate';


//默认超时时间
axios.defaults.timeout = 10000;
//返回其他状态码
axios.defaults.validateStatus = function (status) {
    return status >= 200 && status <= 500;
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;

//http request拦截

declare module 'axios' {
    interface InternalAxiosRequestConfig {
        authorization: boolean
        meta: any
        text: boolean
    }
    interface AxiosRequestConfig {
        authorization?: boolean
    }
}

axios.interceptors.request.use((config) => {
    //headers判断是否需要
    const authorization = config.authorization === false;
    if (!authorization) {
        config.headers['Authorization'] = `Basic ${Base64.encode(`BI:BI_secret`)}`;
    }
    //让每个请求携带token
    const meta = config.meta || {};
    const isToken = meta.isToken === false;
    if (getToken() && !isToken) {
        config.headers['Blade-Auth'] = 'bearer ' + getToken()
    }
    //headers中配置text请求
    if (config.text === true) {
        config.headers["Content-Type"] = "text/plain";
    }
    return config
}, error => {
    return Promise.reject(error)
});
//http response 拦截
axios.interceptors.response.use(async (res) => {
    //关闭 progress bar
    //获取状态码
    const status: number = res.status;//接口请求是否通过
    const code: number = res.data.code || res.status//接口请求结果类型
    const statusWhiteList: number[] = []
    const apiWhiteList: string[] = []
    let message = res.data.msg || res.data.error_description || (typeof res.data === 'string' ? res.data : '') || '未知错误';
    // 尝试解码
    if (res.data && res.data instanceof Blob) {
        if (res.data.type === 'application/json') {
            // 说明返回的不是文件，而是json格式，将json转换
            let _res: any = await new Promise((resolve, reject) => {
                const reader = new FileReader()
                reader.onload = (e) => {
                    let result = e.target?.result as string
                    try {
                        if (validateJSON(result)) {
                            resolve(JSON.parse(result))
                        } else {
                            resolve(result)
                        }
                    } catch (error) {
                        reject(error)
                    }
                }
                reader.readAsText(res.data, 'UTF-8')
            })
            message = _res?.msg || _res?.error_description || (typeof _res === 'string' ? _res : '') || '未知错误';
        }
    }
    const url: string = res.config.url || ''
    //如果在白名单里则自行catch逻辑处理
    if (statusWhiteList.includes(status)) return Promise.reject(res);
    //如果是401则跳转到登录页面
    if (code === 401) { console.log('401') }
    // 如果请求为非200否者默认统一处理
    if (status !== 200) {
        if (url && apiWhiteList.includes(url)) {
            // 接口在api白名单，则不显示警告
            console.error(message)
        } else {
            ElMessage({ message: message, type: 'error' });
        }
        return Promise.reject(new Error(message))
    }
    return res;
}, error => {
    return Promise.reject(new Error(error));
});

export default axios;
